/**
 * 参数映射配置文件
 * 用于将输入参数的字段名映射到中文名称和单位
 * 提供参数显示、格式化和转换的支持
 */

/**
 * 参数映射接口，定义参数的中文名称和单位信息
 */
export interface ParameterMapEntry {
  /** 参数的中文名称 */
  name: string;
  /** 参数的单位（可选） */
  unit?: string;
  /** 小数位数（可选） */
  decimals?: number;
}

/**
 * 参数映射对象类型，键为英文字段名，值为映射配置
 */
export interface ParameterMapping extends Record<string, ParameterMapEntry | undefined> {}

/**
 * 转换后的参数值类型，包含数值和单位
 */
export interface ParameterValueWithUnit {
  value: any;
  unit: string;
}

// 全局基础映射（保留原来的全部内容，只改个名字）
export const BASE_MAPPINGS: ParameterMapping = {
  // 深埋计算参数
  gamma_f: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
  S: { name: '溶洞充填物围岩级别', unit: '' },
  i: { name: '围岩压力增减率', unit: '' },
  B_f: { name: '溶洞宽度', unit: 'm', decimals: 2 },

  // 浅埋计算参数
  gamma_f_shallow: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
  hf_shallow: { name: '溶洞拱部溶洞充填物厚度', unit: 'm', decimals: 2 },
  B_f_shallow: { name: '溶洞宽度', unit: 'm', decimals: 2 },
  lambda_shallow: { name: '充填物侧压力系数', unit: '' },
  theta_shallow: { name: '充填物竖向滑面摩擦角', unit: '°', decimals: 2 },

  // 侧向土压力计算参数
  gamma_f_lateral: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
  h_f_lateral: { name: '厚度', unit: 'm', decimals: 2 },
  h1_lateral: { name: '高度', unit: 'm', decimals: 2 },
  lambda1_lateral: { name: '侧压力系数', unit: '' },

  // 填充物侧压力系数计算参数
  burial_type: { name: '埋藏类型', unit: '' },
  soil_mass: { name: '土体质量', unit: '' },
  slope_direction: { name: '坡度方向', unit: '' },
  varphi_c: { name: '溶洞充填物计算内摩擦角', unit: '°', decimals: 2 },
  alpha: { name: '侧压力系数调整参数', unit: '' },
  phi: { name: '充填物竖向滑面摩擦角', unit: '°', decimals: 2 },
  m: { name: '溶洞充填物表面坡率', unit: '' },
  n: { name: '溶腔壁与隧道溶洞充填物表面交叉点连线的坡率', unit: '' },
  mu: { name: '溶腔壁与溶洞充填物的摩擦系数', unit: '' },
  delta: { name: '侧向土压力与水平线的夹角', unit: '' },
  
  // 穿跨越 / 桁架 / 地基 常用字段
  foundationLength: { name: '基础长度', unit: 'm', decimals: 2 },
  foundationWidth: { name: '基础宽度', unit: 'm', decimals: 2 },
  foundationHeight: { name: '基础高度', unit: 'm', decimals: 2 },
  concreteDensity: { name: '混凝土密度', unit: 'kg/m³', decimals: 1 },
  safetyFactor: { name: '安全系数', unit: '' },
  foundationSectionCoefficient: { name: '基础截面系数', unit: '' },
  foundationInterfaceCoefficient: { name: '基础界面系数', unit: '' },
  trussLateralLoad: { name: '桁架侧向荷载', unit: 'kN', decimals: 2 },
  soilCohesion: { name: '土的粘聚力', unit: 'kPa', decimals: 2 },
  soilFrictionAngle: { name: '土的内摩擦角', unit: '°', decimals: 2 },
  columnWidth: { name: '柱子宽度', unit: 'm', decimals: 2 },
  columnDepth: { name: '柱子深度', unit: 'm', decimals: 2 },
  columnHeight: { name: '柱子高度', unit: 'm', decimals: 2 },
  columnDensity: { name: '柱子密度', unit: 'kg/m³', decimals: 1 },
  columnTopLoad: { name: '柱子顶部荷载', unit: 'kN', decimals: 2 },
  foundationBuriedDepth: { name: '基础埋深', unit: 'm', decimals: 2 },
  columnElasticModulus: { name: '柱子弹性模量', unit: 'kPa', decimals: 2 },
  soilUnitWeight: { name: '土重度', unit: 'kg/m³', decimals: 1 },
  trussLength: { name: '桁架长度', unit: 'm', decimals: 2 },
  trussHeight: { name: '桁架高度', unit: 'm', decimals: 2 },
  trussWidth: { name: '桁架宽度', unit: 'm', decimals: 2 },
  load: { name: '荷载', unit: '' },
  
  // 渣场相关参数
  wasteDumpName: { name: '渣场名称', unit: '' },
  
  // 隧道长度计算参数
  tunnelLength: { name: '隧道长度', unit: 'm', decimals: 2 },
  tunnelDiameter: { name: '隧道直径', unit: 'm', decimals: 2 },
  entranceX: { name: '入洞口X坐标', unit: 'm', decimals: 4 },
  entranceY: { name: '入洞口Y坐标', unit: 'm', decimals: 4 },
  entranceZ: { name: '入洞口Z坐标', unit: 'm', decimals: 4 },
  exitX: { name: '出洞口X坐标', unit: 'm', decimals: 4 },
  exitY: { name: '出洞口Y坐标', unit: 'm', decimals: 4 },
  exitZ: { name: '出洞口Z坐标', unit: 'm', decimals: 4 },
  
  // 倒三角桁架结构计算参数
  triangleTrussTopWidth: { name: '倒三角桁架顶部宽度', unit: 'm', decimals: 2 },
  triangleTrussBottomWidth: { name: '倒三角桁架底部宽度', unit: 'm', decimals: 2 },
  triangleTrussHeight: { name: '倒三角桁架高度', unit: 'm', decimals: 2 },
  triangleTrussSpacing: { name: '倒三角桁架间距', unit: 'm', decimals: 2 },
  triangleTrussMaterial: { name: '倒三角桁架材料', unit: '' },
  
  // 焊缝计算参数
  strengthFactor: { name: '强度系数', unit: '' },
  weldSize: { name: '焊缝尺寸', unit: 'mm', decimals: 2 },
  weldLength: { name: '焊缝长度', unit: 'mm', decimals: 2 },
  weldStrengthValue: { name: '焊缝强度值', unit: 'MPa', decimals: 2 },
  axialForce: { name: '轴向力', unit: 'N', decimals: 2 },
  
  // 配筋计算参数
  columnLength: { name: '柱长', unit: 'mm', decimals: 2 },
  bottomMoment: { name: '柱底弯矩', unit: 'N*mm', decimals: 2 },
  protectiveLayerThickness: { name: '保护层厚度', unit: 'mm', decimals: 2 },
  shearForce: { name: '混凝土抗压强度设计值', unit: 'MPa', decimals: 2 },
  
  // 水流量计算参数
  F: { name: '汇水面积', unit: 'km²', decimals: 2 },
  k_3: { name: '植被及土壤影响系数', unit: '' },
  J: { name: '河道平均坡降', unit: '‰', decimals: 2 },
  n_rainfall: { name: '暴雨递减指数', unit: '' },
  zone: { name: '水文气象分区', unit: '' },
  H6: { name: '6小时点暴雨量', unit: 'mm', decimals: 2 },
  H24: { name: '24小时点暴雨量', unit: 'mm', decimals: 2 },
  
  // 落石冲击计算参数
  mr: { name: '落石质量', unit: 'kg', decimals: 2 },
  Hr: { name: '下落高度', unit: 'm', decimals: 2 },
  Tb: { name: '缓冲层厚度', unit: 'm', decimals: 2 },
  g: { name: '重力加速度', unit: 'm/s²', decimals: 4 },
  Fr2: { name: '冲击荷载', unit: 'kN', decimals: 2 },
  Dr: { name: '落石直径', unit: 'm', decimals: 2 },
  beta: { name: '冲击荷载扩散角', unit: '°', decimals: 2 },
  phi_b: { name: '缓冲层内摩擦角', unit: '°', decimals: 2 },
  Tb2: { name: '缓冲层厚度', unit: 'm', decimals: 2 }
};

// 定义落石冲击相关的映射配置，用于共享
const rockImpactMapping: Partial<ParameterMapping> = {
  mr: { name: '落石质量', unit: 'kg', decimals: 2 },
  Hr: { name: '下落高度', unit: 'm', decimals: 2 },
  Tb: { name: '缓冲层厚度', unit: 'm', decimals: 2 },
  g: { name: '重力加速度', unit: 'm/s²', decimals: 4 },
  Fr2: { name: '冲击荷载', unit: 'kN', decimals: 2 },
  Dr: { name: '落石直径', unit: 'm', decimals: 2 },
  beta: { name: '冲击荷载扩散角', unit: '°', decimals: 2 },
  phi_b: { name: '缓冲层内摩擦角', unit: '°', decimals: 2 },
  Tb2: { name: '缓冲层厚度', unit: 'm', decimals: 2 },
};

// 专属覆盖映射（只写每个计算类型"与基础不同"的部分）
const SPECIAL_MAPPINGS: Record<string, Partial<ParameterMapping>> = {
  'cave-soil-pressure': {
    gamma_f: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
    S: { name: '溶洞充填物围岩级别', unit: '' },
    i: { name: '围岩压力增减率', unit: '' },
    B_f: { name: '溶洞宽度', unit: 'm', decimals: 2 },
  },
  'cave-soil-pressure-shallow': {
    gamma_f_shallow: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
    hf_shallow: { name: '溶洞拱部溶洞充填物厚度', unit: 'm', decimals: 2 },
    B_f_shallow: { name: '溶洞宽度', unit: 'm', decimals: 2 },
    lambda_shallow: { name: '充填物侧压力系数', unit: '' },
    theta_shallow: { name: '充填物竖向滑面摩擦角', unit: '°', decimals: 2 },
  },
  'lateral-soil-pressure': {
    gamma_f_lateral: { name: '溶洞充填物重度', unit: 'kN/m³', decimals: 2 },
    h_f_lateral: { name: '厚度', unit: 'm', decimals: 2 },
    h1_lateral: { name: '高度', unit: 'm', decimals: 2 },
    lambda1_lateral: { name: '侧压力系数', unit: '' },
  },
  'pressure-coefficient': {
    burial_type: { name: '埋藏类型', unit: '' },
    soil_mass: { name: '土体质量', unit: '' },
    slope_direction: { name: '坡度方向', unit: '' },
    varphi_c: { name: '内摩擦角', unit: '°', decimals: 2 },
    alpha: { name: '侧压力系数调整参数', unit: '' },
    phi: { name: '摩擦角', unit: '°', decimals: 2 },
    m: { name: '参数m', unit: '' },
    n: { name: '参数n', unit: '' },
    mu: { name: '泊松比', unit: '' },
    delta: { name: '参数delta', unit: '' },
  },
  'waterflow': {
    F: { name: '汇水面积', unit: 'km²', decimals: 2 },
    k_3: { name: '植被及土壤影响系数', unit: '' },
    J: { name: '河道平均坡降', unit: '‰', decimals: 2 },
    n_rainfall: { name: '暴雨递减指数', unit: '' },
    zone: { name: '水文气象分区', unit: '' },
    H6: { name: '6小时点暴雨量', unit: 'mm', decimals: 2 },
    H24: { name: '24小时点暴雨量', unit: 'mm', decimals: 2 },
  },
  'rock-impact': rockImpactMapping,
  'rock-impact-strength': rockImpactMapping,
  'truss-column-reinforcement': {
    columnWidth: { name: '柱宽', unit: 'mm', decimals: 2 },
    columnHeight: { name: '柱高', unit: 'mm', decimals: 2 },
    axialForce: { name: '轴向力', unit: 'N', decimals: 2 },
    bottomMoment: { name: '柱底弯矩', unit: 'N*mm', decimals: 2 },
    shearForce: { name: '混凝土抗压强度设计值', unit: 'MPa', decimals: 2 },
  },
  'crossing-foundation-calculation': {
    columnWidth: { name: '柱子宽度', unit: 'm', decimals: 2 },
    columnHeight: { name: '柱子高度', unit: 'm', decimals: 2 },
    foundationInterfaceCoefficient: { name: '基础界面系数', unit: '' },
  },
  'tunnel-lenth-calculation': {
    entranceX: { name: '入洞口X坐标', unit: 'm', decimals: 4 },
    entranceY: { name: '入洞口Y坐标', unit: 'm', decimals: 4 },
    entranceZ: { name: '入洞口Z坐标', unit: 'm', decimals: 4 },
    exitX: { name: '出洞口X坐标', unit: 'm', decimals: 4 },
    exitY: { name: '出洞口Y坐标', unit: 'm', decimals: 4 },
    exitZ: { name: '出洞口Z坐标', unit: 'm', decimals: 4 },
  },
};

// 映射缓存，提升性能并保持对象引用稳定
const mappingCache = new Map<string | undefined, ParameterMapping>();

// 核心合并函数
const getMapping = (type?: string): ParameterMapping => {
  if (mappingCache.has(type)) return mappingCache.get(type)!;

  const result = type && SPECIAL_MAPPINGS[type]
    ? { ...BASE_MAPPINGS, ...SPECIAL_MAPPINGS[type] }
    : { ...BASE_MAPPINGS };

  mappingCache.set(type, result);
  return result;
};

// 为保持兼容性，重新添加getParameterMapping函数
export const getParameterMapping = (calculationType?: string): ParameterMapping => {
  try {
    // 参数验证
    if (calculationType && typeof calculationType !== 'string') {
      console.warn('获取参数映射失败: 计算类型必须是字符串');
      return BASE_MAPPINGS;
    }
    
    return getMapping(calculationType);
  } catch (error) {
    console.error('获取参数映射失败:', error);
    return BASE_MAPPINGS;
  }
};

// 精简版工具函数
export const getParameterName = (key: string, type?: string) =>
  getMapping(type)[key]?.name ?? BASE_MAPPINGS[key]?.name ?? key;

export const getParameterUnit = (key: string, type?: string) =>
  getMapping(type)[key]?.unit ?? BASE_MAPPINGS[key]?.unit ?? '';

export const getParameterDecimals = (key: string, type?: string) =>
  getMapping(type)[key]?.decimals ?? BASE_MAPPINGS[key]?.decimals;

export const transformInputsWithNamesAndUnits = <T extends Record<string, any>>(
  inputs: T,
  type?: string
): Record<string, ParameterValueWithUnit> => {
  const mapping = getMapping(type);
  const result: any = {};

  for (const key in inputs) {
    const cfg = mapping[key] ?? BASE_MAPPINGS[key];
    const name = cfg?.name ?? key;
    result[name] = {
      value: inputs[key],
      unit: cfg?.unit ?? ''
    };
  }
  return result;
};

// 重载版本以保持兼容性
export function formatParameterDisplay(value: any, key: string, type?: string): string;
export function formatParameterDisplay(value: any, unit?: string, decimals?: number): string;
export function formatParameterDisplay(
  value: any,
  keyOrUnit?: string,
  typeOrDecimals?: string | number
): string {
  if (value == null) return '-';

  // 如果第二个参数是 string 且第三个也是 string → 按 key + type 处理
  if (typeof keyOrUnit === 'string' && typeof typeOrDecimals === 'string') {
    const decimals = getParameterDecimals(keyOrUnit, typeOrDecimals);
    const unit = getParameterUnit(keyOrUnit, typeOrDecimals);
    const num = typeof value === 'number' && decimals != null ? value.toFixed(decimals) : value;
    return unit ? `${num} ${unit}` : `${num}`;
  }

  // 否则走老逻辑
  const unit = (typeof keyOrUnit === 'string' ? keyOrUnit : '') || '';
  const decimals = typeof typeOrDecimals === 'number' ? typeOrDecimals : undefined;
  const num = typeof value === 'number' && decimals != null ? value.toFixed(decimals) : value;
  return unit ? `${num} ${unit}` : `${num}`;
};

// 为保持完全兼容性，添加原始的参数映射对象
export const parameterMappings: ParameterMapping = { ...BASE_MAPPINGS };

// 计算类型中文名常量
export const CALCULATION_TYPE_NAMES: Record<string, string> = {
  'cave-soil-pressure': '溶洞土压力计算（深埋）',
  'cave-soil-pressure-shallow': '溶洞土压力计算（浅埋）',
  'lateral-soil-pressure': '侧向土压力计算',
  'pressure-coefficient': '侧压力系数计算',
  'waterflow': '水流量计算',
  'rock-impact': '落石冲击计算',
  'rock-impact-strength': '落石冲击强度计算',
  'truss-column-reinforcement': '桁架柱配筋计算',
  'crossing-foundation-calculation': '穿越基础计算',
  'tunnel-lenth-calculation': '隧道长度计算',
};

export const getCalculationTypeName = (type: string) =>
  CALCULATION_TYPE_NAMES[type] ?? type;

// 保留原有函数以保持兼容性
export const getSupportedCalculationTypes = (): string[] => {
  return Object.keys(CALCULATION_TYPE_NAMES);
};

export const isCalculationTypeSupported = (calculationType: string): boolean => {
  return typeof calculationType === 'string' && 
    calculationType.trim() !== '' && 
    Object.keys(CALCULATION_TYPE_NAMES).includes(calculationType);
};